package com.etang.guosaia20201004;

import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.bizideal.smarthome.socket.SocketClient;
import com.etang.guosaia20201004.tools.CodeView;
import com.etang.guosaia20201004.tools.DiyToast;
import com.etang.guosaia20201004.tools.MyDataBaseHelper;

public class MainActivity extends AppCompatActivity {

    private Handler handler;
    private Runnable timeRunnable;
    private ImageView iv_code_show;
    private TextView tv_loign_codecount;
    private Button btn_login;
    private CountDownTimer timer;
    private SharedPreferences sharedPreferences;
    private EditText et_user, et_pass, et_yanzheng;
    private CheckBox cb_rember, cb_autologin;
    private LinearLayout line_progress;
    private int number = 0;
    private ProgressBar pg_1;
    private TextView tv_number;
    private MyDataBaseHelper dbHelper;
    private SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initUser();
        cb_autologin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cb_rember.setChecked(true);
                } else {
                    cb_rember.setChecked(false);
                }
            }
        });
        cb_rember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {

                } else {
                    cb_rember.setChecked(false);
                }
            }
        });
        timer = new CountDownTimer(15000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tv_loign_codecount.setText(String.valueOf(millisUntilFinished / 1000 % 60) + "秒后刷新");
            }

            @Override
            public void onFinish() {
                timer.start();
                iv_code_show.setImageBitmap(CodeView.createBitmap());
            }
        }.start();
        iv_code_show.setImageBitmap(CodeView.createBitmap());
        iv_code_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_code_show.setImageBitmap(CodeView.createBitmap());
            }
        });
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_user.getText().toString().isEmpty()) {
                    DiyToast.showToast(getApplicationContext(), "用户名不能为空");
                } else if (et_pass.getText().toString().isEmpty()) {
                    DiyToast.showToast(getApplicationContext(), "密码不能为空");
                } else if (et_yanzheng.getText().toString().isEmpty()) {
                    DiyToast.showToast(getApplicationContext(), "验证码不能为空");
                } else {
                    if (et_yanzheng.getText().toString().equalsIgnoreCase(CodeView.code_String)) {
                        Cursor cursor = db.rawQuery("SELECT * FROM USER WHERE USERNAME = ? AND PASSWARD = ?", new String[]{et_user.getText().toString(), et_pass.getText().toString()});
                        if (cursor.moveToNext()) {
                            if (cb_autologin.isChecked() && cb_rember.isChecked()) {
                                sharedPreferences.edit().putBoolean("autologin", true).putBoolean("rember", true).putString("user", et_user.getText().toString()).putString("pass", et_pass.getText().toString()).commit();
                            } else if (cb_rember.isChecked()) {
                                sharedPreferences.edit().putBoolean("autologin", false).putBoolean("rember", true).putString("user", et_user.getText().toString()).putString("pass", et_pass.getText().toString()).commit();
                            } else {
                                sharedPreferences.edit().putBoolean("autologin", false).putBoolean("rember", false).putString("user", et_user.getText().toString()).putString("pass", et_pass.getText().toString()).commit();
                            }
                            iv_code_show.setVisibility(View.INVISIBLE);
                            tv_loign_codecount.setVisibility(View.INVISIBLE);
                            btn_login.setVisibility(View.INVISIBLE);
                            line_progress.setVisibility(View.VISIBLE);
                            startHandler();
                        } else {
                            DiyToast.showToast(getApplicationContext(), "用户名或密码输入错误");
                        }
                    } else {
                        DiyToast.showToast(getApplicationContext(), "验证码输入错误");
                    }
                }
            }
        });
    }

    private void startHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                pg_1.setProgress(number);
                tv_number.setText(String.valueOf(number));
                handler.postDelayed(timeRunnable, 10);
            }
        };
        timeRunnable = new Runnable() {
            @Override
            public void run() {
                number++;
                Message msg = handler.obtainMessage();
                if (number < 100) {
                    handler.sendMessage(msg);
                } else {
                    handler.removeCallbacks(timeRunnable);
                    startActivity(new Intent(MainActivity.this
                            , IndexActivity.class));
                    finish();
                }
            }
        };
        handler.post(timeRunnable);
    }

    private void initUser() {
        if (sharedPreferences.getBoolean("autologin", false) == true) {
            try {
                SocketClient.ip = sharedPreferences.getString("ip", null);
                startActivity(new Intent(getApplicationContext(), IndexActivity.class));
                finish();
            } catch (Exception e) {
                sharedPreferences.edit().putString("ip", "18.1.10.2");
                SocketClient.ip = sharedPreferences.getString("ip", null);
            }
        }
        if (sharedPreferences.getBoolean("rember", false) == true) {
            et_user.setText(sharedPreferences.getString("user", null));
            et_pass.setText(sharedPreferences.getString("pass", null));
            cb_rember.setChecked(true);
        }
    }

    /**
     * 绑定控件
     */
    private void initView() {
        cb_rember = (CheckBox) findViewById(R.id.cb_rember);
        cb_autologin = (CheckBox) findViewById(R.id.cb_autologin);
        tv_number = (TextView) findViewById(R.id.tv_login_number);
        pg_1 = (ProgressBar) findViewById(R.id.pg_login);
        line_progress = (LinearLayout) findViewById(R.id.line_progress);
        btn_login = (Button) findViewById(R.id.btn_login);
        et_pass = (EditText) findViewById(R.id.et_pass);
        et_yanzheng = (EditText) findViewById(R.id.et_yazheng);
        et_user = (EditText) findViewById(R.id.et_user);
        tv_loign_codecount = (TextView) findViewById(R.id.tv_loign_codecount);
        iv_code_show = (ImageView) findViewById(R.id.iv_code_show);
        dbHelper = new MyDataBaseHelper(getApplicationContext(), "info.db", null, 2);
        db = dbHelper.getWritableDatabase();
        line_progress.setVisibility(View.INVISIBLE);
        sharedPreferences = getSharedPreferences("rember", MODE_PRIVATE);
        try {
            if (sharedPreferences.getString("smo_state", null).isEmpty()) {

            }
        } catch (Exception e) {
            sharedPreferences.edit().putString("smo_state", "开").commit();
            sharedPreferences.edit().putString("ill_state", "开").commit();
            sharedPreferences.edit().putString("temp_state", "开").commit();
            sharedPreferences.edit().putString("per_state", "开").commit();
            sharedPreferences.edit().putString("co_state", "开").commit();
            sharedPreferences.edit().putString("per_values", "5").commit();
            sharedPreferences.edit().putString("smo_values", "100").commit();
            sharedPreferences.edit().putString("co_low_values", "1000").commit();
            sharedPreferences.edit().putString("co_max_values", "1000").commit();
            sharedPreferences.edit().putString("ill_low_values", "200").commit();
            sharedPreferences.edit().putString("ill_max_values", "300").commit();
            sharedPreferences.edit().putString("temp_low_values", "18").commit();
            sharedPreferences.edit().putString("temp_max_values", "26").commit();
        }

    }
}